package com.ly.mpayment.persist.service.yidong;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.CookieRedis;
import com.ly.mpayment.core.util.DateUtils;
import com.ly.mpayment.core.util.ListRange;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.yidong.GameOrder;
import com.ly.mpayment.persist.entity.yidong.MobileOrders;
import com.ly.mpayment.persist.hibernate.Page;
import com.ly.mpayment.persist.service.AbstractService;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.mobile.IMobileService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
@Service
public class MobileOrdersServiceImpl extends AbstractService<MobileOrders, Serializable> implements IMobileOrdersService {


	@Autowired
	IGameOrderService gameService;
	
	@Autowired
	IUporderService upOrderService;

	@Autowired
	IMobileService mobileService;

	@Autowired
	IDownRechargeFlowService flowService;

	@Autowired
	ThreadPoolTaskExecutor taskExecutor;

	@Autowired
	IDownShopInfoService shopService;

	
	@Override
	public boolean saveMobileOrders(MobileOrders orders) {
		if(orders != null){
			this.saveOrUpdate(orders);
			return true;
		}
		return false;
	}

	@Override
	public boolean updateMobileOrders(MobileOrders orders) {
		if(orders != null){
			this.updateEntity(orders);
			return true;
		}
		return false;
	}
	
	@Override
	public GameOrder updateMobileOrdersGame(MobileOrders mobilesOrder,JSONObject json,GameOrder order,String type) {
		try {
			if(mobilesOrder != null){
				
//				mobilesOrder.setMatching(1);
//				this.updateEntity(mobilesOrder);
				//查询订单是否存在 如果存在则返回失败
				order = new GameOrder();
				order.setOrderId(json.getString("orderId"));
				order.setOrderAmount(json.getBigDecimal("orderAmount"));
				order.setOrderTime(DateUtils.getNowDate());
				order.setMobileOrdersId(mobilesOrder.getMobileOrdersId());
				order.setOrderState(1);
				order.setCallback(json.getString("callback"));
				order.setType(type);
				order.setUserId(json.getString("userId"));
				return this.gameService.saveGameOrder(order);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public MobileOrders findByNumberId(String numberId) {
		return this.findUnique("select m from MobileOrders m where m.numberPool.numberPoolId = ?", numberId);
	}

	@Override
	public MobileOrders findById(String id) {
		return this.findUnique("select o from MobileOrders o where o.mobileOrdersId = ? ", id);
	}
	
	@Override
	public MobileOrders findByFetchNumberPool(String id) {
		return this.findUnique("select o from MobileOrders o left join fetch o.numberPool where o.mobileOrdersId = ?", id);
	}

	@Override
	public Page<MobileOrders> pageOrders(Map<String, Object> parameters, int start, int pageSize) {
		
		String hql = "select m from MobileOrders m left join fetch m.numberPool where 1 = 1  #[ and m.mobileOrdersId = :mobileOrdersId ]#  #[ and m.province = :province ]# " 
				+ " #[ and m.city = :city ]#  #[ and m.serialNo = :serialNo ]# "
				+ " #[ and m.phoneNo = :phoneNo ]#  #[ and m.chargeMoney = :chargeMoney ]# "
				+ " #[ and m.orderStatus = :orderStatus ]#  #[ and m.callResult = :noticeStatus ]#  #[ and m.matching = :matching ]# #[ and m.orderId = :orderId ]#  ";
		if(parameters.containsKey(":startTime")){
			hql += " and m.systemTime >= '".concat(parameters.get(":startTime").toString()).concat("'");
			parameters.remove(":startTime");
		}
		if(parameters.containsKey(":endtime")){
			hql += " and m.systemTime <= '".concat(parameters.get(":endtime").toString()).concat("'");
			parameters.remove(":endtime");
		}
		hql += " order by m.systemTime desc ";
		
		return this.findPageByNamed(hql, parameters, start, pageSize);		
	}

	@Override
	public MobileOrders findByOrderId(String id) {
		return this.findUnique("select o from MobileOrders o left join fetch o.numberPool where o.orderId = ?", id);
	}
	
	@Override
	public MobileOrders findByTeleOrderId(String id) {
		return this.findUnique("select o from MobileOrders o  where o.orderId = ?", id);
	}

	@Override
	public List<MobileOrders> findMonthNotEnd(String phoneNum,int orderStatus,int operator) {
		return this.find(" select o from MobileOrders o left join fetch o.numberPool n  where n.mobilePhone = ? and o.orderStatus = ? and o.operator = 1 order by o.qrTime", phoneNum,orderStatus);
	}

	@Override
	public MobileOrders findByFailtId(String id) {
		return this.findUnique("select o from MobileOrders o where  o.mobileOrdersId = ?", id);
	}

	@Override
	public MobileOrders findBySuccessId(String id) {
		return this.findUnique("select o from MobileOrders o where o.orderStatus = 1 and o.mobileOrdersId = ?", id);
	}
	
	@Override
	public MobileOrders findBySuccessYiDongId(String id) {
		return this.findUnique("select o from MobileOrders o where o.orderStatus = 1 and o.mobileOrdersId = ?", id);
	}
	

	@Override
	public List<MobileOrders> findNoticeStatus(int matching, int orderStatus,int operator) {
		return this.find("select o from MobileOrders o left join fetch o.numberPool n where o.matching = ? and o.orderStatus = ? and o.operator = ? order by o.qrTime", matching,orderStatus,operator);
	}

	/**
	 * 查询订单为 0的订单 并且等于指定价格的订单 升序排序  未匹配的订单 matching = 0
	 */
	@Override
	public  MobileOrders findRechargeStatusPrice(int orderStatus,BigDecimal chargeMoney,int type,String payType) { 
		MobileOrders orders = null;
		if(payType != null){
			if(type == 1){
				//查询2分钟内的订单  当前时间减去指定分钟 是否小于订单生成时间 2019-10-06 21:38:54 2019-10-06 21:39:54 
				String time = DateUtils.toLongDate(DateUtils.subtractSeconds(Integer.valueOf(CookieRedis.get("weixinpaytime")), DateUtils.getNowDate()));
				//优化为分页
				ListRange<MobileOrders> range = this.findPageDataByNamed(String.format("select m from MobileOrders m left join fetch m.numberPool where m.orderStatus = "+orderStatus+" and m.chargeMoney = "+chargeMoney+" and m.matching = 0 and m.qrTime >= '"+time+"' and m.type = '"+payType+"' order by m.qrTime"), new HashMap<String, Object>(), 0, 1);
				if(range != null && range.getList() != null && range.getList().size() > 0){
					orders = range.getList().get(0);
					if(orders != null){
						orders.setMatching(1);
						this.updateMobileOrders(orders);
						return orders;
					}
				}
				return null;
			}else if(type == 2){
				//查询2分钟内的订单  当前时间减去指定分钟 是否小于订单生成时间 2019-10-06 21:38:54 2019-10-06 21:39:54 
				String time = DateUtils.toLongDate(DateUtils.subtractSeconds(Integer.valueOf(CookieRedis.get("telecomorderquerytime")), DateUtils.getNowDate()));
				//优化为分页
				ListRange<MobileOrders> range = this.findPageDataByNamed(String.format("select m from MobileOrders m left join fetch m.numberPool where m.orderStatus = "+orderStatus+" and m.chargeMoney = "+chargeMoney+" and m.matching = 0 and m.qrTime >= '"+time+"' and m.type = '"+payType+"' order by m.qrTime"), new HashMap<String, Object>(), 0, 1);
				if(range != null && range.getList() != null && range.getList().size() > 0){
					orders = range.getList().get(0);
					if(orders != null){
						orders.setMatching(1);
						this.updateMobileOrders(orders);
						return orders;
					}
				}
				return null;
			}
		}else{
			if(type == 1){
				//查询2分钟内的订单  当前时间减去指定分钟 是否小于订单生成时间 2019-10-06 21:38:54 2019-10-06 21:39:54 
				Date time = (DateUtils.subtractSeconds(Integer.valueOf(CookieRedis.get("weixinpaytime")), DateUtils.getNowDate()));
				//优化为分页
//				return this.findPageDataByNamed("select m from MobileOrders m left join fetch m.numberPool where m.orderStatus =  "+ orderStatus + " and m.chargeMoney = "+ chargeMoney.toString() +" and m.matching = 0 and m.systemTime >= '"+time+"' order by m.systemTime", new HashMap<String, Object>(), 0, 1);
				orders =  this.findOneObject("select m from MobileOrders m left join fetch m.numberPool where m.orderStatus = ? and m.chargeMoney = ? and m.matching = 0 and m.qrTime >= ? order by m.qrTime", orderStatus,chargeMoney,time);
				if(orders != null){
					orders.setMatching(1);
					this.updateMobileOrders(orders);
				}
				return orders;
			}else if(type == 2){
				//查询2分钟内的订单  当前时间减去指定分钟 是否小于订单生成时间 2019-10-06 21:38:54 2019-10-06 21:39:54 
				Date time = (DateUtils.subtractSeconds(Integer.valueOf(CookieRedis.get("telecomorderquerytime")), DateUtils.getNowDate()));
				//优化为分页
//				return this.findPageDataByNamed("select m from MobileOrders m left join fetch m.numberPool where m.orderStatus =  "+ orderStatus + " and m.chargeMoney = "+ chargeMoney.toString() +" and m.matching = 0 and m.systemTime >= '"+time+"' order by m.systemTime", new HashMap<String, Object>(), 0, 1);
				orders = this.findOneObject("select m from MobileOrders m  where m.orderStatus = ? and m.chargeMoney = ? and m.matching = 0 and m.qrTime >= ?   order by m.qrTime", orderStatus,chargeMoney,time);
				if(orders != null){
					orders.setMatching(1);
					this.updateMobileOrders(orders);	
				}
				return orders;
			}
		}
		return null;
	}

	@Override
	public List<MobileOrders> findRechargeStatusPrice(int orderStatus) {
		return this.find("select m from MobileOrders m where m.orderStatus = ?  order by m.qrTime ", orderStatus);
	}

	/**
	 * 查询订单创建2分钟未被匹配充值 过期的订单失败回去
	 */
	@Override
	public List<MobileOrders> findNotMatching(int orderStatus, int matching) {
		Date time = (DateUtils.subtractSeconds(Integer.valueOf(CookieRedis.get("orderouttime")), DateUtils.getNowDate()));
		return this.find("select m from MobileOrders m where m.orderStatus = ?  and m.matching = ? and m.qrTime < ?  order by m.qrTime", orderStatus,matching,time);
	}

	@Override
	public List<MobileOrders> findNotMatchingOrder(int orderStatus, int matching) {
		Date time = (DateUtils.subtractSeconds(Integer.valueOf(CookieRedis.get("orderouttime")), DateUtils.getNowDate()));
		return this.find("select m from MobileOrders m where m.orderStatus = ?  and m.matching = ? and m.systemTime < ?  order by m.systemTime", orderStatus,matching,time);
	}

	/**
	 * 查询订单下单2分钟
	 */
	@Override
	public List<MobileOrders> findMatchingOrder(int orderStatus, int matching) {
		//匹配成功后失效时间
//		Date time = (DateUtils.subtractionMinutes(Integer.valueOf(CookieRedis.get("matchingOrdertime")), DateUtils.getNowDate()));
		//统一检查订单时间
		Date time = (DateUtils.subtractionMinutes(Integer.valueOf(CookieRedis.get("telecomchecktime")), DateUtils.getNowDate()));
		return this.find("select m from MobileOrders m left join fetch m.numberPool where m.orderStatus = ?  and m.matching = ? and m.qrTime < ?  order by m.qrTime", orderStatus,matching,time);
	}

	@Override
	public boolean updateMobileOrders(MobileOrders pool, String msg) {
		if(pool != null){
			pool.setRemark(msg);
			this.updateEntity(pool);
			return true;
		}
		return false;
	}
	
	
	/**
	 * 失败订单 订单状态 1 未支付 0 等待支付 2支付成功 3支付失败 4充值成功 5充值失败
	 * 
	 * @param numberPoolId
	 * @param mobileOrdersId
	 * @param order
	 * @param msg
	 * @param bool
	 *            是否通知游戏 true 通知 false 为不通知，正常流程失败需要通知， 下单失败或者二维码获取失败不需要通知
	 */
//	public void failtMobileOrder(String mobileOrdersId, UpOrder order, String msg, String orderStatus,boolean temp) {
//		if (orderStatus.equals("5")) {
//			MobileOrders mobileOrder = this.findByFailtId(mobileOrdersId);
//			if (mobileOrder != null && mobileOrder.getMatching() == 0 && mobileOrder.getOrderStatus() == 1)  {
//				mobileOrder.setOrderStatus(Integer.valueOf(orderStatus));
//				mobileOrder.setEndTime(DateUtils.getNowDate());
//				mobileOrder.setRemark(msg);
//				this.updateMobileOrders(mobileOrder);
//
////				flowService.orderHanlderFailt(order, upOrderService, flowService, shopService, taskExecutor, msg);
//
//				try {
//					flowService.orderHanlderFailt(order, upOrderService, flowService, shopService, taskExecutor, msg);
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//					logger.error("事务回滚，重新开始...................");
//					failtMobileOrder(mobileOrdersId, order, msg, orderStatus, temp);
//				}
//				
//				GameOrder gameOrder = gameService.findByMobileOrderId(mobileOrder.getMobileOrdersId());
//				if(gameOrder != null){
//					updateGameOrderNotNotice(mobileOrder, orderStatus,temp,msg);
//				}
//			} else {
//				logger.error("订单错误或者已经匹配成功4...............");
//				mobileOrder.setRemark(mobileOrder.getRemark() == null ? "订单状态异常。。人工核实4" : mobileOrder.getRemark().concat("订单状态异常。。人工核实4"));
//				this.updateMobileOrders(mobileOrder);
//			}
//			if(order != null){
//				// 提交失败
//				CookieRedis.rmKey(order.getUporderuuid());
//				CookieRedis.rmKey(mobileOrdersId);
//			}
//		}
//	}
	
	/**
	 * 手动失败订单调用
	 * @param mobileOrdersId
	 * @param order
	 * @param msg
	 * @param orderStatus
	 * @param temp
	 */
//	public void failtHandlerMobileOrder(String mobileOrdersId, UpOrder order, String msg, String orderStatus,boolean temp) {
//		if (orderStatus.equals("5")) {
//			MobileOrders mobileOrder = this.findByFailtId(mobileOrdersId);
//			if (mobileOrder != null )  {
//				mobileOrder.setOrderStatus(Integer.valueOf(orderStatus));
//				mobileOrder.setEndTime(DateUtils.getNowDate());
//				mobileOrder.setRemark(msg);
//				this.updateMobileOrders(mobileOrder);
//
//				
//
//				try {
//					flowService.orderHanlderFailt(order, upOrderService, flowService, shopService, taskExecutor, msg);
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//					logger.error("事务回滚，重新开始...................");
//					failtHandlerMobileOrder(mobileOrdersId, order, msg, orderStatus, temp);
//				}
//				
////				flowService.orderHanlderFailt(order, upOrderService, flowService, shopService, taskExecutor, msg);
//
//				GameOrder gameOrder = gameService.findByMobileOrderId(mobileOrder.getMobileOrdersId());
//				if(gameOrder != null){
//					updateGameOrderNotNotice(mobileOrder, orderStatus,temp,msg);
//				}
//			} else {
//				logger.error("订单错误或者已经匹配成功4...............");
////				mobileOrder.setRemark(mobileOrder.getRemark() == null ? "订单状态异常。。人工核实4" : mobileOrder.getRemark().concat("订单状态异常。。人工核实4"));
////				this.updateMobileOrders(mobileOrder);
//			}
//			if(order != null){
//				// 提交失败
//				CookieRedis.rmKey(order.getUporderuuid());
//				CookieRedis.rmKey(mobileOrdersId);
//			}
//		}
//	}
	
//	public void failtMobileOrderError(String mobileOrdersId, UpOrder order, String msg, String orderStatus,boolean temp) {
//		if (orderStatus.equals("5")) {
//			MobileOrders mobileOrder = this.findByFailtId(mobileOrdersId);
//			if (mobileOrder != null && mobileOrder.getOrderStatus() != 4 )  {
//				mobileOrder.setOrderStatus(Integer.valueOf(orderStatus));
//				mobileOrder.setEndTime(DateUtils.getNowDate());
//				mobileOrder.setRemark(msg);
//				this.updateMobileOrders(mobileOrder);
//
////				flowService.orderHanlderFailt(order, upOrderService, flowService, shopService, taskExecutor, msg);
//				
//				try {
//					flowService.orderHanlderFailt(order, upOrderService, flowService, shopService, taskExecutor, msg);
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//					logger.error("事务回滚，重新开始...................");
//					failtMobileOrderError(mobileOrdersId, order, msg, orderStatus, temp);
//				}
//				
//				logger.error("failtMobileOrderError..............."+mobileOrder.getPhoneNo());
//				GameOrder gameOrder = gameService.findByMobileOrderId(mobileOrder.getMobileOrdersId());
//				if(gameOrder != null){
//					updateGameOrderNotNotice(mobileOrder, orderStatus,temp,msg);
//				}
//			} else {
//				
//				if(mobileOrder != null){
//					mobileOrder.setRemark(mobileOrder.getRemark() == null ? "订单状态异常。。人工核实3" : mobileOrder.getRemark().concat("订单状态异常。。人工核实3"));
//					this.updateMobileOrders(mobileOrder);
//				}else{
//					logger.error("订单错误或者已经匹配成功3...............");
//				}
//			}
//			if(order != null){
//				// 提交失败
//				CookieRedis.rmKey(order.getUporderuuid());
//				CookieRedis.rmKey(mobileOrdersId);
//			}
//		}
//	}

	
//	public void failtMobileOrderMatch(String mobileOrdersId, UpOrder order, String msg, String orderStatus,boolean temp) {
//		if (orderStatus.equals("5")) {
//			MobileOrders mobileOrder = this.findByFailtId(mobileOrdersId);
//			if (mobileOrder != null && mobileOrder.getMatching() == 1 && mobileOrder.getOrderStatus() == 1 && mobileOrder.getOrderStatus() != 4 )  {
//				mobileOrder.setOrderStatus(Integer.valueOf(orderStatus));
//				mobileOrder.setEndTime(DateUtils.getNowDate());
//				mobileOrder.setRemark(msg);
//				this.updateMobileOrders(mobileOrder);
//				if(order != null && order.getStatus() == Config.status[0]){
//					try {
//						flowService.orderHanlderFailt(order, upOrderService, flowService, shopService, taskExecutor, msg);
//					} catch (Exception e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//						logger.error("事务回滚，重新开始...................");
//						failtMobileOrderMatch(mobileOrdersId, order, msg, orderStatus, temp);
//					}
//				}
//				
//	
//				GameOrder gameOrder = gameService.findByMobileOrderId(mobileOrder.getMobileOrdersId());
//				if(gameOrder != null){
//					updateGameOrderNotNotice(mobileOrder, orderStatus,temp,msg);
//				}
//			} else {
//				logger.error("订单错误或者已经匹配成功1...............");
//				mobileOrder.setRemark(mobileOrder.getRemark() == null ? "订单状态异常。。人工核实1" : mobileOrder.getRemark().concat("订单状态异常。。人工核实1"));
//				this.updateMobileOrders(mobileOrder);
//			}
//			if(order != null){
//				// 提交失败
//				CookieRedis.rmKey(order.getUporderuuid());
//				CookieRedis.rmKey(mobileOrdersId);
//			}
//		}
//	}
	
//	
//	public void updateGameOrderNotNotice(MobileOrders mobileOrder, String orderStatus,boolean temp,String msg) {
//		if (mobileOrder != null) {
//			GameOrder gameOrder = gameService.findByMobileOrderId(mobileOrder.getMobileOrdersId());
//			if (gameOrder != null && gameOrder.getOrderState() == 1) {
//				gameOrder.setOrderState(Integer.valueOf(orderStatus));
//				if (orderStatus.equals("2")) {
//					gameOrder.setRechargeTime(DateUtils.getNowDate());
//					gameOrder.setPayTime(DateUtils.getNowDate());
//				}
//				gameOrder.setRemark(msg);
//				logger.info("更新游戏订单状态:"+gameOrder.getOrderId()+","+orderStatus);
//				gameService.updateGameOrder(gameOrder);
//				
//				// true 需要通知 订单不等于空 也需要通知
//				if (mobileOrder.getMatching() == 1 && temp) {
//					gameOrderRest.callGame(gameOrder);
//				}
//			}
//		}
//	}
 
	
	
	/**
	 * 成功订单
	 * 
	 * @param numberPoolId
	 * @param mobileOrdersId
	 * @param order
	 * @param msg
	 */
//	public void successMobileOrder(String mobileOrdersId, UpOrder order, String msg, String orderStatus,String paySuccess) {
//		MobileOrders mobileOrder = this.findBySuccessId(mobileOrdersId);
//		if (mobileOrder != null && mobileOrder.getOrderStatus() == 1 && orderStatus.equals("4") && mobileOrder.getMatching() == 1) {
//			// 更新订单
//			mobileOrder.setOrderStatus(Integer.valueOf(orderStatus));
//			mobileOrder.setEndTime(DateUtils.getNowDate());
//			mobileOrder.setRemark(msg != null ? msg : "充值成功");
//			mobileOrder.setPaySuccess(paySuccess);
//			this.updateMobileOrders(mobileOrder);
//			
//			try {
//				// 先回调充值订单
//				flowService.orderHanlder(order, upOrderService, flowService, shopService, taskExecutor,	mobileOrder.getOrderId());
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				logger.error("事务回滚，重新开始...................");
//				successMobileOrder(mobileOrdersId, order, msg, orderStatus, paySuccess);
//			}
//			
//			
//			// 在发送到游戏方
//			updateGameOrder(mobileOrder, orderStatus,mobileOrder.getSerialNo());
//			if(order != null){
//				// 提交失败
//				CookieRedis.rmKey(order.getUporderuuid());
//				CookieRedis.rmKey(mobileOrdersId);
//			}
//		} else {
//			logger.error("successMobileOrder_error:" + order.getUpphonenum());
//			logger.error("订单错误或者已经匹配成功2...............");
//			mobileOrder.setRemark("订单状态异常2...。人工核实2");
//			this.updateMobileOrders(mobileOrder);
//		}
//	}
	

	/**
	 * 更新游戏单据状态
	 * 
	 * @param mobileOrder
	 * @param orderStatus
	 */
//	public void updateGameOrder(MobileOrders mobileOrder, String orderStatus,String msg) {
//		if (mobileOrder != null) {
//			GameOrder gameOrder = gameService.findByMobileOrderId(mobileOrder.getMobileOrdersId());
//			if (gameOrder != null && orderStatus.equals("4") && mobileOrder.getOrderStatus() == 4 && gameOrder.getOrderState() == 1) {
//				gameOrder.setOrderState(Integer.valueOf(orderStatus));
//				gameOrder.setPayTime(DateUtils.getNowDate());
//				gameOrder.setRechargeTime(DateUtils.getNowDate());
//				gameOrder.setRemark(msg);
//				logger.info("更新游戏订单状态:"+gameOrder.getOrderId()+","+orderStatus);
//				gameService.updateGameOrder(gameOrder);
//				gameOrderRest.callGame(gameOrder);
//			}
//		}
//	}


}
